package com.xr.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 对象工具类
 *
 * @author XR FZH
 */
public class XrObjectUtil {

    /**
     * 判断对象中的字段值是否全部为空
     *
     * @param object 对象
     * @return boolean
     */
    public static boolean checkOfAllNull(Object object) {
        if (ObjectUtils.isEmpty(object)) {
            return true;
        }
        List<Object> list = new ArrayList<>();
        Class<?> clazz = object.getClass();
        List<Field> fields = new ArrayList<>();
        while (ObjectUtils.isNotEmpty(clazz)) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        try {
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = field.get(object);
                if (ObjectUtils.isNotEmpty(fieldValue) && StringUtils.isNotBlank(fieldValue.toString())) {
                    list.add(fieldValue);
                }
            }
            if (list.size() > 0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 判断对象是否为空
     *
     * @param object 对象
     * @return boolean
     */
    private static boolean isEmpty(Object object) {
        if (object == null) {
            return true;
        }
        if (object instanceof String && (object.toString().equals(""))) {
            return true;
        }
        if (object instanceof Collection && ((Collection<?>) object).isEmpty()) {
            return true;
        }
        if (object instanceof Map && ((Map<?, ?>) object).isEmpty()) {
            return true;
        }
        return object instanceof Object[] && ((Object[]) object).length == 0;
    }

    /**
     * 判断对象是否为非空
     *
     * @param object 对象
     * @return boolean
     */
    private static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

}
